package com.hdd.hll.quartz.job;

import com.alibaba.fastjson.JSON;
import com.hdd.hll.common.response.Result;
import com.hdd.hll.common.utils.AesEncryptUtils;
import com.hdd.hll.common.utils.OpenApiLogUtil;
import com.hdd.hll.modules.sendtruck.web.dto.PushWeightBillDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 提煤数据推送Job实现类
 *
 * @author jw
 */
@Component
@Slf4j
public class PushWeightBillJob implements Job {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${jd.api.url}")
    private String jdApiUrl;


    @Value("${api.path.suffix.sendTruck.pickUpGoods}")
    private String pickUpGoods;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Map map = context.getJobDetail().getJobDataMap();
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            // 渠道参数，执行相应的业务流程
            log.info("执行JD调拨单信息同步接口推送任务，入参：{}", entry.getValue());
            pushWeightBill(JSON.parseObject(entry.getValue(), PushWeightBillDto.class));
        }
    }


    public Result<String> pushWeightBill(PushWeightBillDto pushWeightBillDto) {
        StringBuilder pushWeightParamValidRes = pushWeightParamValidRes(pushWeightBillDto);
        Result<String> result = new Result<>();
        if (!StringUtils.isBlank(pushWeightParamValidRes)) {
            result.setSuccess(false);
            result.setMsg(pushWeightParamValidRes.toString());
            OpenApiLogUtil.logResponse(result);
            return result;
        }
        Result<String> decryptRes = null;
        try {
            String vehicleReleaseEncryptRes = restTemplate.postForObject(jdApiUrl + pickUpGoods, AesEncryptUtils.encrypt(JSON.toJSONString(pushWeightBillDto)), String.class);
            decryptRes = JSON.parseObject(AesEncryptUtils.decrypt(vehicleReleaseEncryptRes), Result.class);
            log.info("请求JD矿区车辆提煤接口，Msg：{}", decryptRes);
        } catch (Exception e) {
            log.error("请求JD矿区车辆提煤接口异常，Msg：{}", e.getMessage());
            if (Objects.isNull(decryptRes)) {
                decryptRes = new Result<>();
            }
            decryptRes.setSuccess(false);
            decryptRes.setMsg(String.format("请求JD矿区车辆提煤接口异常，Msg：%s", e.getMessage()));
        }

        OpenApiLogUtil.logResponse(decryptRes);
        return decryptRes;
    }

    private StringBuilder pushWeightParamValidRes(PushWeightBillDto pushWeightBillDto) {
        StringBuilder dataValidateResult = new StringBuilder();
        int operationType = pushWeightBillDto.getOperationType();
        if (operationType == 1) {
            if (StringUtils.isBlank(pushWeightBillDto.getInboundTime())) {
                dataValidateResult.append("获取过空磅时间异常：inboundTime must not be null or empty;");
            }
            if (com.hdd.hll.common.utils.StringUtils.isNullOrEmpty(pushWeightBillDto.getTare())) {
                dataValidateResult.append("获取过空磅重量异常：tare must not be null or empty;");
            }
        }

        if (operationType == 2) {
            if (StringUtils.isBlank(pushWeightBillDto.getInboundTime())) {
                dataValidateResult.append("获取过空磅时间异常：inboundTime must not be null or empty;");
            }
            if (com.hdd.hll.common.utils.StringUtils.isNullOrEmpty(pushWeightBillDto.getTare())) {
                dataValidateResult.append("获取过空磅重量异常：tare must not be null or empty;");
            }
            if (StringUtils.isBlank(pushWeightBillDto.getOutboundTime())) {
                dataValidateResult.append("获取过重磅时间异常：outboundTime must not be null or empty;");
            }
            if (com.hdd.hll.common.utils.StringUtils.isNullOrEmpty(pushWeightBillDto.getGrossWeight())) {
                dataValidateResult.append("获取过重磅重量异常：grossWeight must not be null or empty;");
            }
            if (com.hdd.hll.common.utils.StringUtils.isNullOrEmpty(pushWeightBillDto.getNetWeight())) {
                dataValidateResult.append("获取净重异常：netWeight must not be null or empty;");
            }
        }
        return dataValidateResult;
    }
}
